using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Xml.Schema;
using System.IO;

namespace ESBSimpleSamples.ServiceClient.Generator.WSDL
{
    /// <summary>
    /// Represents the metadata for a WSDL endpoint
    /// </summary>
    public class WSDLMetadata
    {
        private string _name;
        /// <summary>
        /// Name
        /// </summary>
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private string _type;
        /// <summary>
        /// Type
        /// </summary>
        public string Type
        {
            get { return _type; }
            set { _type = value; }
        }

        private string _source;
        /// <summary>
        /// Source
        /// </summary>
        public string Source
        {
            get { return _source; }
            set
            {
                _source = value;
                if (!_source.EndsWith("?wsdl", StringComparison.CurrentCultureIgnoreCase))
                {
                    _source = string.Concat(_source, "?wsdl");
                }
            }
        }

        public string TargetNamespace
        {
            get
            {
                return this.Proxy.ServiceDescription.TargetNamespace;
            }
        }

        public XmlSchema Schema
        {
            get
            {
                return this.Proxy.ServiceDescription.Types.Schemas[0];
            }
        }

        public string SchemaText
        {
            get
            {
                StringWriter writer = new StringWriter();
                XmlTextWriter xmlWriter = new XmlTextWriter(writer);
                this.Schema.Write(xmlWriter);
                xmlWriter.Flush();
                return writer.ToString();
            }
        }

        private DynamicProxy _proxy;
        private DynamicProxy Proxy
        {
            get
            {
                if (this._proxy == null)
                {
                    this._proxy = new DynamicProxy(new Uri(this._source));
                }
                return this._proxy;
            }
        }

        private WSDLMethodCollection _methods;
        public WSDLMethodCollection Methods
        {
            get
            {
                if (this._methods == null)
                {
                    this._methods = new WSDLMethodCollection();
                    foreach (MethodInfo methodInfo in this.Proxy.GetWebMethods())
                    {
                        this._methods.Add(new WSDLMethod(methodInfo, this.Proxy.ServiceDescription, this.Schema));
                    }
                }
                return this._methods;
            }
        }
    }
}
